//
//  AnalyzeTableViewCell.swift
//  MoodDiary
//
//  Created by OVIX on 2020/12/10.
//

import UIKit

enum AnalyzeCellType {
//    case moodChange
    case moodAnalyze
//    case activityAnalyze
    case weatherAnalyze
}

protocol AnalyzeTableViewCellDelegate: class {
    func analyzeTableViewCellShare(type: AnalyzeCellType?)
}

class AnalyzeTableViewCell: UITableViewCell {
    
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var btn: UIButton!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var collectionView: UICollectionView!
    
    var delegate: AnalyzeTableViewCellDelegate?
    
    var analyzeType: AnalyzeCellType?
    
    var moodDicArr: [[String: Int]]?
    var weatherDicArr: [[String: Int]]?
    
    var isMonth: Bool?
    
    var beginEndDay = "" {
        didSet {
            var str = ""
            
            if moodDicArr != nil {
                str = "心情分布 " + beginEndDay
            }
            if weatherDicArr != nil {
                str = "天气分布 " + beginEndDay
            }
            
            if isMonth == false {
                let attStr = NSMutableAttributedString(string: str)
                attStr.addAttributes([.font: UIFont.systemFont(ofSize: 14.0, weight: .light), .foregroundColor: UIColor.hexColor(hex: "#D4D4D4")], range: NSMakeRange(4, beginEndDay.count + 1))
                label.attributedText = attStr
                return
            }
            
            let attStr = NSMutableAttributedString(string: (str as NSString).substring(to: 7) + "月")
            attStr.addAttributes([.font: UIFont.systemFont(ofSize: 14.0, weight: .light), .foregroundColor: UIColor.hexColor(hex: "#D4D4D4")], range: NSMakeRange(5, 2 + 1))
            label.attributedText = attStr
        }
    }
    
    var moodDic: [String: Int]? {
        didSet {
            if analyzeType == .moodAnalyze {
                
                label.text = "心情分布"
                dealMoodData()
            }
        }
    }
    
    var weatherDic: [String: Int]? {
        didSet {
            if analyzeType == .weatherAnalyze {
                
                label.text = "天气分布"
                
                dealWeatherData()
                
            }
            
        }
    }
    
    func dealMoodData() {
        
        //把value取出来 按从大到小排序 然后剩下的内容按照固定顺序排序
        var array: [[String: Int]] = []
        
        if moodDic != nil {
            let sortedDic = moodDic!.sorted(by: {$0.1 > $1.1})
            
            for (key, value) in sortedDic {
                if value > 0 {
                    array.append([key: value])
                }
            }
        }
        
        if array.count < 10 {
            
            var keys: [String] = []
            
            for dict2 in array {
                keys.append(dict2.keys.first ?? "")
            }
            
            let shouldContainKeys = ["开心", "得意", "暖心", "惊喜", "甜蜜", "充实", "平静", "尴尬", "伤心", "无聊", "不安", "生气", "流泪", "疲倦", "梦境", "分裂", "孤独", "不知道"]
            
            for key in shouldContainKeys {
                if keys.contains(key) == false {
                    array.append([key: 0])
                }
            }
            
            array = ([[String: Int]])(array.prefix(10))
            
        }
        
        moodDicArr = array
        collectionView.reloadData()
        
        if array.count > 0 {
            label2.isHidden = false
            
//            if isMonth == true {
//                label2.text = "本月最多心情: " + "\(array.first?.keys.first ?? "")"
//            } else {
//                label2.text = "本周最多心情: " + "\(array.first?.keys.first ?? "")"
//            }
            
            label2.text = "本" + (isMonth == true ? "月": "周") + "最多心情" + (array.first?.keys.first ?? "")
            
        } else {
            label2.isHidden = true
        }
        
    }
    
    func dealWeatherData() {
        
        //把value取出来 按从大到小排序 然后剩下的内容按照固定顺序排序
        var array: [[String: Int]] = []
        
        if weatherDic != nil {
            let sortedDic = weatherDic!.sorted(by: {$0.1 > $1.1})
            
            for (key, value) in sortedDic {
                if value > 0 {
                    array.append([key: value])
                }
            }
        }
        
        if array.count < 8 {
            
            var keys: [String] = []
            
            for dict2 in array {
                keys.append(dict2.keys.first ?? "")
            }
            
            let shouldContainKeys = ["晴天", "多云", "阴天", "雨", "雪", "雾", "浮尘", "沙尘暴"]
            
            for key in shouldContainKeys {
                if keys.contains(key) == false {
                    array.append([key: 0])
                }
            }
            
            array = ([[String: Int]])(array.prefix(8))
            
        }
        
        weatherDicArr = array
        collectionView.reloadData()
        
//        if weatherDic != nil {
//            label2.isHidden = false
//            label2.text = "本周最多天气: " + "\(array.first?.keys.first ?? "")"
//        } else {
//            label2.isHidden = true
//        }
        
        label2.isHidden = true
        
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: "AnalyzeCollectionViewCell", bundle: .main), forCellWithReuseIdentifier: "AnalyzeCollectionViewCell")
        
        bgView.layer.cornerRadius = 12.0
        bgView.layer.shadowOpacity = 1.0
        bgView.layer.shadowOffset = CGSize(width: 0, height: 0)
        bgView.layer.shadowRadius = 2.0
        bgView.layer.shadowColor = UIColor.init(white: 0.6, alpha: 0.4).cgColor
    }
    
}

extension AnalyzeTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let margin = 5.0
        let itemHeight = Double(collectionView.height)
        
        if analyzeType == .moodAnalyze {
            let itemWidth = (Double(collectionView.width) - margin * 9.0) / 10.0
            return CGSize(width: itemWidth, height: itemHeight)
        }
        if analyzeType == .weatherAnalyze {
            let itemWidth = (Double(collectionView.width) - margin * 7.0) / 8.0
            return CGSize(width: itemWidth, height: itemHeight)
        }
        
        return .zero
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 5.0 }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if analyzeType == .moodAnalyze { return moodDicArr?.count ?? 0 }
        if analyzeType == .weatherAnalyze { return weatherDicArr?.count ?? 0 }
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: AnalyzeCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "AnalyzeCollectionViewCell", for: indexPath) as! AnalyzeCollectionViewCell
        
        if analyzeType == .moodAnalyze {
            cell.maxInt = moodDicArr?.first?.values.first ?? 0
            cell.moodDic = moodDicArr?[indexPath.row]
        } else if analyzeType == .weatherAnalyze {
            cell.maxInt = weatherDicArr?.first?.values.first ?? 0
            cell.weatherDic = weatherDicArr?[indexPath.row]
        }
        cell.analyzeType = analyzeType
        
        return cell
    }
    
}


extension AnalyzeTableViewCell {
    
    @IBAction func action(_ sender: Any) {
        delegate?.analyzeTableViewCellShare(type: analyzeType)
    }
    
}
